<!--
 * @Descripttion: (机器号基础表/PM_Base_Machine)
 * @Author: (admin)
 * @Date: (2025-08-29)
-->
<template>
  <div>
    <el-form :model="queryParams" label-position="right" inline ref="queryRef" v-show="showSearch" @submit.prevent>
      <el-form-item>
        <el-form-item label="全型号" prop="pmName">
            <el-select v-model="queryParams.pmName" placeholder="全型号" filterable style="width: 140px">
              <el-option label="全部"  value="" />
              <el-option v-for="dict in  modelTypeOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
            </el-select>
          </el-form-item>

 
      <el-form-item label="老机器号" prop="machineNum" >
        <el-input v-model="queryParams.machineNum" placeholder="请输老机器号" />
      </el-form-item>
        <el-form-item label="新机器号" prop="displayMachineNum">
        <el-input v-model="queryParams.displayMachineNum" placeholder="请输入新机器号" />
      </el-form-item>
        <el-button icon="search" type="primary" @click="handleQuery">{{ $t('btn.search') }}</el-button>
        <el-button icon="refresh" @click="resetQuery">{{ $t('btn.reset') }}</el-button>
      </el-form-item>
    </el-form>
    <!-- 工具区域 -->
    <el-row :gutter="15" class="mb10">
      <el-col :span="1.5">
        <el-button type="primary" v-hasPermi="['pmbasemachine:add']" plain icon="plus" @click="handleAdd">
          {{ $t('btn.add') }}
        </el-button>
      </el-col>
    
      <el-col :span="1.5">
        <el-button type="warning" plain icon="download" @click="handleExport" v-hasPermi="['pmbasemachine:export']">
          {{ $t('btn.export') }}
        </el-button>
      </el-col>
             <span style="color: red;">老机器仅作为参考，可通过原规则查询新生成的机器编号</span> 
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
     
    </el-row>

    <el-table
      :data="dataList"
      v-loading="loading"
      ref="table"
      border
      header-cell-class-name="el-table-header-cell"
      highlight-current-row
      @sort-change="sortChange"
      >
          <el-table-column label="操作" width="320">
        <template #default="scope">
          <el-button type="primary" size="small" icon="view" title="详情" @click="handlePreview(scope.row)">查看</el-button>
          <el-button type="success" size="small" icon="edit" title="编辑" v-hasPermi="['pmbasemachine:edit']" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button type="primary" size="small" icon="download" title="二维码" @click="handleShowQr(scope.row)">二维码</el-button>
          <!-- <el-button type="success" size="small" icon="log" title="打印"   @click="handleShowQr(scope.row)">打印</el-button> -->
        <el-button type="danger" size="small" icon="delete" width="20" title="删除" v-hasPermi="['pmbasemachine:delete']" @click="handleDelete(scope.row)"></el-button>
        </template>
      </el-table-column>
      <el-table-column prop="displayMachineNum" label="机器编号" width="220">
    <template #default="scope">
      <span>{{scope.row.displayMachineNum}}</span>
      <el-button 
        type="text" 
        icon="copy-document" 
        @click="copyMachineNum(scope.row.displayMachineNum)"
        title="复制"
      ></el-button>
    </template>
  </el-table-column>
      <!-- <el-table-column prop="displayMachineNum" label="机器编号" width="150" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('displayMachineNum')"/> -->
       <el-table-column prop="pmName" label="型号" align="center" width="100":show-overflow-tooltip="true" v-if="columns.showColumn('pmName')"/>
       <el-table-column prop="pmYear" label="年份" align="center" width="80":show-overflow-tooltip="true" v-if="columns.showColumn('pmYear')"/>
      <el-table-column prop="pmBatch" label="批次" align="center" width="80":show-overflow-tooltip="true" v-if="columns.showColumn('pmBatch')"/>
      <el-table-column prop="pmSum" label="台数" align="center" width="80":show-overflow-tooltip="true" v-if="columns.showColumn('pmSum')"/>
     
       <el-table-column prop="cusName" label="客户名称" align="center"  width="150" :show-overflow-tooltip="true" v-if="columns.showColumn('cusName')"/>
      <el-table-column prop="cusQty" label="订单数量" align="center" width="50":show-overflow-tooltip="true" v-if="columns.showColumn('cusQty')"/>
     
      <el-table-column prop="cusOrderId" label="订单号"  width="120" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('cusOrderId')"/> -->
        <el-table-column prop="cusRemark" label="要求" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('cusRemark')"/> -->
     
      <el-table-column prop="pmModel" label="字母位" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('pmModel')"/>
      <el-table-column prop="pmSpec" label="数字位" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('pmSpec')"/>
 <el-table-column prop="def" label="备注" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('def')"/> 
       <!-- <el-table-column prop="def1" label="Def1" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('def1')"/>
      <el-table-column prop="def2" label="Def2" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('def2')"/>  -->
      <el-table-column prop="createTime" label="操作时间" :show-overflow-tooltip="true"  v-if="columns.showColumn('createTime')"/>
      <el-table-column prop="createName" label="操作人" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('createName')"/>

        <el-table-column prop="machineNum" label="老机器号" width="150"   align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('machineNum')"/>
    </el-table>
    <pagination :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />


    <el-dialog :title="title" :lock-scroll="false" v-model="open" >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">


          <el-col :lg="12">
            <el-form-item label="机器编号"  prop="displayMachineNum">
              <el-input v-model="form.displayMachineNum" disabled placeholder="自动生成" />
            </el-form-item>
          </el-col>
 <el-col :lg="12">
            <el-form-item label="型号" prop="pmName">
              <el-select v-model="form.pmName" placeholder="请选择型号" filterable   :disabled="isupdate"   @change="tplSelectChange">
                <el-option v-for="dict in modelTypeOptions" :key="dict.dictValue" :label="dict.dictLabel" :value=" (dict.dictValue)" />
              </el-select>
            </el-form-item>


            <!-- <el-form-item label="全型号" prop="pMName">
              
              <el-input v-model="form.pMName" placeholder="请输入全型号" />
            </el-form-item> -->
          </el-col>

          <el-col :lg="12">
            <el-form-item label="字母位" prop="pmModel">
              <el-input v-model="form.pmModel" disabled placeholder="根据型号自动拆分" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="数字位" prop="pmSpec">
              <el-input v-model="form.pmSpec" disabled placeholder="根据型号自动拆分" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="年份" prop="pmYear">
             <el-input-number  v-model="form.pmYear" :disabled="isupdate" controls-position="right" :min="0" :max="99"   @change="tplinputChange"/>  
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="批次" prop="pmBatch">
              <el-input-number  v-model="form.pmBatch" :disabled="isupdate"  controls-position="right" :min="0" :max="99" @change="tplinputChange"/>
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="台数" prop="pmSum">
             <el-input-number  v-model="form.pmSum" :disabled="isupdate" controls-position="right" :min="0" :max="99" @change="tplinputChange"/> 
            </el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="客户名称" prop="cusName">
              <el-input v-model="form.cusName" placeholder="请输入客户" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="订单数量" prop="cusQty">
              <el-input v-model="form.cusQty" placeholder="请输入订单数量" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="订单要求" prop="cusRemark">
              <el-input v-model="form.cusRemark" placeholder="请输入订单要求" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="订单号" prop="cusOrderId">
              <el-input v-model="form.cusOrderId" placeholder="请输入订单号" />
            </el-form-item>
          </el-col>

         

          <el-col :lg="12">
            <el-form-item label="备注" prop="Def">
              <el-input v-model="form.def" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
 

          
        </el-row>
      </el-form>
      <template #footer v-if="opertype != 3">
        <el-button text @click="cancel">{{ $t('btn.cancel') }}</el-button>
        <el-button type="primary" :loading="state.submitLoading" @click="submitForm">{{ $t('btn.submit') }}</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="qropen" :title="qrTitle">
       <div ref="imgContainerRef" id="imgContainer" class="qrCode"></div>
       <template #footer>
         <el-button type="primary" @click="downloadQrCode">下载二维码</el-button>
       </template>
    </el-dialog>
  </div>
</template>

<script setup name="pmbasemachine">
import { listPmBaseMachine,
 addPmBaseMachine, delPmBaseMachine, 
 updatePmBaseMachine,getPmBaseMachine, 
 } 
  from '@/api/buss/pmbasemachine.js'
import QRCode from 'qrcodejs2-fixes'
const { proxy } = getCurrentInstance()
const ids = ref([])
const isupdate = ref(false)
const loading = ref(false)
const showSearch = ref(true)
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  sort: 'MachineNum',
  sortType: 'asc',
  pmName: '',
  machineNum: '',
  displayMachineNum: '',
})
const columns = ref([
  { visible: false, align: 'center', type: '', prop: 'machineNum', label: '老机器号'  ,showOverflowTooltip: true  },
  { visible: true, align: 'center', type: '', prop: 'displayMachineNum', label: '机器编号'  ,showOverflowTooltip: true  },
  { visible: true, align: 'center', type: '', prop: 'cusName', label: '客户名称'  ,showOverflowTooltip: true  },
  { visible: false, align: 'center', type: '', prop: 'cusQty', label: '订单数量'  ,showOverflowTooltip: true  },
  { visible: false, align: 'center', type: '', prop: 'cusRemark', label: '订单要求'  ,showOverflowTooltip: true  },
  { visible: true, align: 'center', type: '', prop: 'cusOrderId', label: '订单号'  ,showOverflowTooltip: true  },
  { visible: true, align: 'center', type: '', prop: 'pmName', label: '型号'  ,showOverflowTooltip: true  },
  { visible: false, align: 'center', type: '', prop: 'pmModel', label: '字母位'  ,showOverflowTooltip: true  },
  { visible: false, align: 'center', type: '', prop: 'pmSpec', label: '数字位'  ,showOverflowTooltip: true  },
  { visible: true, align: 'center', type: '', prop: 'pmYear', label: '年份'  ,showOverflowTooltip: true  },
  { visible: true, align: 'center', type: '', prop: 'pmBatch', label: '批次'  ,showOverflowTooltip: true  },
  { visible: true, align: 'center', type: '', prop: 'pmSum', label: '台数'  ,showOverflowTooltip: true  },
  { visible: false, align: 'center', type: '', prop: 'def', label: '备注'  ,showOverflowTooltip: true  },
  // { visible: false, align: 'center', type: '', prop: 'def1', label: 'Def1'  ,showOverflowTooltip: true  },
  // { visible: false, align: 'center', type: '', prop: 'def2', label: 'Def2'  ,showOverflowTooltip: true  },
  { visible: false, align: 'center', type: '', prop: 'createTime', label: '操作时间'  ,showOverflowTooltip: true  },
  { visible: false, align: 'center', type: '', prop: 'createName', label: '操作人'  ,showOverflowTooltip: true  },
  //{ visible: false, prop: 'actions', label: '操作', type: 'slot', width: '160' }
])
const total = ref(0)
const dataList = ref([])
const queryRef = ref()
const defaultTime = ref([new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)])


var dictParams = [
]
function tplSelectChange(value) {
  //console.log(value)
  form.value.pmModel = value.replace(/[^a-zA-Z]/g, '');
  form.value.pmSpec = value.replace(/[^0-9]/g, '').padStart(6-form.value.pmModel.length, '0');
}
function tplinputChange(value) {
  // 确保所有必需字段都有值
  if (!form.value.pmModel || !form.value.pmSpec) {
    proxy.$modal.msgWarning('请先选择型号');
    return;
  }
  
  // 验证输入值是否有效
  const year = form.value.pmYear || 0;
  const batch = form.value.pmBatch || 0;
  const sum = form.value.pmSum || 0;
  
  // 生成随机码并更新显示机器号
  try {
    // 确保年份、批次、台数不足2位时补零
    const year = String(form.value.pmYear || 0).padStart(2, '0');
    const batch = String(form.value.pmBatch || 0).padStart(2, '0');
    const sum = String(form.value.pmSum || 0).padStart(2, '0');
    form.value.displayMachineNum = `${form.value.pmModel}${form.value.pmSpec}${generateRandomCode(year + batch + sum)}`;
  } catch (error) {
    console.error('生成机器号失败:', error);
    //proxy.$modal.msgError('生成机器号失败，请检查输入');
  }
}
function getList(){
  loading.value = true
  listPmBaseMachine(queryParams).then(res => {
    const { code, data } = res
    if (code == 200) {
      dataList.value = data.result
      total.value = data.totalNum
      loading.value = false
    }
  })
}

// 查询
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}
 function copyMachineNum(machineNum) {
      // 创建一个临时的 textarea 元素
      const textarea = document.createElement('textarea');
      // 设置 textarea 的值为要复制的文本
      textarea.value = machineNum;
      // 将 textarea 添加到文档中（不会显示，因为位置在屏幕外）
      document.body.appendChild(textarea);
      // 选中 textarea 中的文本
      textarea.select();
      // 执行复制命令
      document.execCommand('copy');
      // 移除 textarea 元素
      document.body.removeChild(textarea);
      
   // 可选：显示复制成功的提示
          proxy.$modal.msgSuccess("机器编号已复制！") 
    }
// 重置查询操作
function resetQuery(){
  proxy.resetForm("queryRef")
  handleQuery()
}
// 自定义排序
function sortChange(column) {
  var sort = undefined
  var sortType = undefined

  if (column.prop != null && column.order != null) {
    sort = column.prop
    sortType = column.order

  }
  queryParams.sort = sort
  queryParams.sortType = sortType
  handleQuery()
}

/*************** form操作 ***************/
const formRef = ref()
const title = ref('')
const qrTitle = ref('查看二维码')
const qropen = ref(false); // 控制扫码登录弹窗的显示与隐藏 
// 操作类型 1、add 2、edit 3、view
const opertype = ref(0)
const open = ref(false)
const state = reactive({
  single: true,
  multiple: true,
  submitLoading: false,
  form: {},
  rules: { 
    pmName: [
      { required: true, message: '型号不能为空', trigger: 'blur' }, { min: 2, max: 15, message: '型号必选', trigger: 'blur' }],
     pmYear: [
      { required: true, message: '年份不能为空', trigger: 'blur' }],
 
    pmBatch: [
      { required: true, message: '批次不能为空', trigger: 'blur' }],
    pmSum: [
      { required: true, message: '台数不能为空', trigger: 'blur' }],
      

  },
  options: {
  }
})

const { form, rules, options, single, multiple } = toRefs(state)

// 关闭dialog
function cancel(){
  open.value = false
  qropen.value = false
  reset()
}
 
function handleShowQr(row) {
  qropen.value = true;
  //qrtitle.value = '查看二维码'+row.displayMachineNum;
  nextTick(() => {
    const element = document.getElementById('imgContainer');
    if (element) {
      generateCode(element, row);
    } else {
      console.error('二维码容器元素未找到');
    }
  });
}


// 生成二维码
const currentQrCode = ref(null);

function generateCode(element,row) {
  qropen.value = true; 
  element.innerHTML = '正在生成中...';
  element.innerHTML = '';  
   // 生成HTML表格字符串
  const tableHtml =
`机器编号:${row.displayMachineNum} 
订 单 号:${row.cusOrderId} 
客户名称: ${row.cusName} 
订单数量: ${row.cusQty} 
订单要求: ${row.cusRemark}`;
  currentQrCode.value = new QRCode(element, {
    text: tableHtml,
    width: 160,
    height: 160
  });
}

function downloadQrCode() {
  if (!currentQrCode.value) return;
  
  const canvas = document.querySelector('#imgContainer canvas');
  if (!canvas) return;
  
  const link = document.createElement('a');
  link.download = '二维码.png';
  link.href = canvas.toDataURL('image/png');
  link.click();
}
 

// 重置表单
function reset() {
  form.value = {
    machineNum: null,
    displayMachineNum: null,
    cusName: null,
    cusQty: null,
    cusRemark: null,
    cusOrderId: null,
    pmName: null,
    pmModel: null,
    pmSpec: null,
    pmYear:  new Date().getFullYear().toString().slice(-2), // 获取当前公历年份（四位数字）,截取后两位作为批次号
    pmBatch: null,
    pmSum: null,
    def: null,
    def1: null,
    def2: null,
    createTime: null,
    createName: null,
  };
  proxy.resetForm("formRef")
}

/**
 * 查看
 * @param {*} row
 */
function handlePreview(row) {
  reset()
    const id = row.machineNum
    getPmBaseMachine(id).then((res) => {
    const { code, data } = res
    if (code == 200) {
      open.value = true
      title.value = '查看'
      opertype.value = 3
      form.value = {
        ...data,
      }
    }
  })
}

// 添加按钮操作
function handleAdd() {
  isupdate.value = false;
  reset();
  open.value = true
  state.submitLoading = false
  title.value = '添加机器号基础表'
  opertype.value = 1
}
// 修改按钮操作
function handleUpdate(row) {
  isupdate.value = true;
  reset()
  const id = row.machineNum || ids.value
  getPmBaseMachine(id).then((res) => {
    const { code, data } = res 
    if (code == 200) {
      open.value = true
      title.value = '修改机器号基础表'
      opertype.value = 2
      form.value = {
        ...data,
           // Ensure numeric fields are properly formatted 
           pmYear: data.pmYear ? parseInt(data.pmYear) : null,
        pmBatch: data.pmBatch ? parseInt(data.pmBatch) : null,
        pmSum: data.pmSum ? parseInt(data.pmSum) : null

      };
    }
  })
}
   // 从原始代码生成关联代码（示例算法）
     // 生成随机代码
     const generateRandomCode = (numStr) => {
       try {
         // 确保输入是字符串
         const str = numStr.toString().padStart(6, '0').slice(0, 6);
         let encrypted = '';
         
         for (let i = 0; i < 6; i++) {
           const digit = parseInt(str[i]) || 0;
           
           // 数字转字母 (0→A, 1→B, ..., 9→J)
           let char = String.fromCharCode(65 + (digit % 10));
           
           // 根据位置进行ASCII码移位
           if (i % 2 === 0) {
             char = String.fromCharCode(char.charCodeAt(0) + i + 1);
           } else {
             char = String.fromCharCode(char.charCodeAt(0) - i);
           }
           
           // 确保结果在数字和大写字母范围内
           let code = char.charCodeAt(0);
           if (code < 48) code += 10;
           if (code > 57 && code < 65) code -= 7;
           if (code > 90) code -= 13;
           
           encrypted += String.fromCharCode(code);
         }
         
         // 检查第一位是否为数字0，如果是则替换为随机字母
         if (encrypted.charAt(0) === '0') {
           encrypted = getRandomLetter() + encrypted.slice(1);
         }
         
         return encrypted;
       } catch (error) {
         console.error('生成随机码出错:', error);
         proxy.$modal.msgError('生成随机码失败');
         return 'ERROR';
       }
     };
 
  // 获取随机大写字母
                const getRandomLetter = () => {
                    const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                    return letters[Math.floor(Math.random() * letters.length)];
                };
                // 添加&修改 表单提交
function submitForm() {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      state.submitLoading = true
      // 确保年份、批次、台数不足2位时补零
      const year = String(form.value.pmYear).padStart(2, '0');
      const batch = String(form.value.pmBatch).padStart(2, '0');
      const sum = String(form.value.pmSum).padStart(2, '0');
      form.value.machineNum = form.value.pmModel + form.value.pmSpec + year + batch + sum;
      //form.value.displayMachineNum = form.value.pmModel + form.value.pmSpec +generateRandomCode(padleft form.value.pmYear + form.value.pmBatch+form.value.pmSum);
      if (form.value.machineNum != undefined && opertype.value === 2) {
        updatePmBaseMachine(form.value).then((res) => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addPmBaseMachine(form.value).then((res) => {
            proxy.$modal.msgSuccess("新增成功")
            open.value = false
            getList()
          })
          .finally(() => {
            setTimeout(() => {
              state.submitLoading = false
            }, 800)
          })
      }
    }
  })
}

// 删除按钮操作
function handleDelete(row) {
  const Ids = row.machineNum || ids.value

  proxy
    .$confirm('是否确认删除参数编号为"' + Ids + '"的数据项？', "警告", {
      confirmButtonText: proxy.$t('common.ok'),
      cancelButtonText: proxy.$t('common.cancel'),
      type: "warning",
    })
    .then(function () {
      return delPmBaseMachine(Ids)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess("删除成功")
    })
}



// 导出按钮操作
function handleExport() {
  proxy
    .$confirm("是否确认导出机器号基础表数据项?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
    .then(async () => {
      await proxy.downFile('/Buss/PmBaseMachine/export', { ...queryParams })
    })
}
const modelTypeOptions = ref([])
proxy.getDicts('sys_pro_model').then((response) => {
  modelTypeOptions.value = response.data
})

handleQuery()
</script>
<style lang="scss"  scoped>
.qrCode {
  width: 160px;
  height: 160px;
  line-height: 160px;
  margin: 0 auto;
}
</style>